<template>
  <div class="ueditor" v-loading="editorUpLoading">
    <el-upload style="display: none;" name="file" :before-upload="beforeUpload" :on-exceed="handleExceed" :multiple="true" :on-progress="uploadProgress" :limit="limit" :action="action" :headers="headers" :accept="accept" :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadError">
      <el-button size="small" type="primary" icon="el-icon-upload2" :id="fileUploadId">导入</el-button>
    </el-upload>
    <div class="ueditor-container" :id="ueditorId"></div>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      default: "",
    },
    height: {
      type: Number,
      default: 400,
    },
    autoHeight: {
      type: Boolean,
      default: false,
    },
    type: "",
    zIndex: {
      type: Number,
      default: 2000,
    }
  },
  data() {
    return {
      ueditorId: "ueditor",
      fileUploadId: "fileUpload",
      limit: 0,
      headers: {
        Authorization: this.func.getToken(),
      },
      action: this.configs.main + "/api/OSS/PutLocalFile",
      editor: '', // 存放实例化的UEditor实例，方便this调用
      editorContent: '',
      editorUpLoading: false,
      editorConfig: {
        // 如果需要上传功能,找后端小伙伴要服务器接口地址
        // serverUrl: this.$config.baseUrl + 'ueditor/ueditorConfig',
        // serverUrl: 'http://localhost:8090/ueditor/ueditorConfig',
        // 你的UEditor资源存放的路径,相对于打包后的index.html
        UEDITOR_HOME_URL: '/static/ueditor/',
        // toolbars: [[
        //   'fullscreen', 'source', '|', 'undo', 'redo', '|',
        //   'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
        //   'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
        //   'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
        //   'directionalityltr', 'directionalityrtl', 'indent', '|',
        //   'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
        //   'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
        //   'simpleupload', 'emotion', 'scrawl', 'map', 'gmap', 'insertframe', 'insertcode', 'pagebreak', 'template', 'background', '|',
        //   'horizontal', 'date', 'time', 'spechars', '|',
        //   'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
        //   'print', 'preview', 'searchreplace', 'help'
        // ]],
        toolbars: [[
          'source', 'undo', 'redo', '|',
          'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
          'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'inserttable', 'deletetable',
          'customstyle', 'paragraph', 'fontfamily', 'fontsize', 'indent', '|',
          'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
          'touppercase', 'tolowercase', 'link', '|',
          'simpleupload', 'emotion', 'insertframe', '|',
          'horizontal', 'spechars',
        ]],
        fontsize: [12, 13, 14, 15, 16, 18, 20, 24, 28, 36],
        // 编辑器不自动被内容撑高
        autoHeightEnabled: this.autoHeight,
        // 工具栏是否可以浮动
        autoFloatEnabled: true,
        // 初始容器高度
        initialFrameHeight: this.height,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 关闭自动保存
        enableAutoSave: false,
        elementPathEnabled: false,
        wordCount: true,
        zIndex: this.zIndex,
      },
      accept: ".png,.jpg,.jpeg,.gif,.bmp,.gif,.mp4,.avi,.wmv,.remvb,.mp3,.wav",
    }
  },
  watch: {
    value() {
      if (this.editor && this.value !== this.editorContent) {
        this.editor.setContent(this.value || "");
      }
    }
  },
  mounted() {
    this.func.setSession("action", this.action);
    let temp = new Date().getTime();
    this.ueditorId = "ueditor" + temp;
    this.fileUploadId = "fileUploadId" + temp;
    this.init();
  },
  methods: {
    init() {
      let timer = setTimeout(() => {
        this.editor = UE.getEditor(this.ueditorId, this.editorConfig);
        this.editor.ready(() => {
          this.editor.execCommand('fontfamily', '微软雅黑'); //字体
          if (this.value) {
            this.editor.setContent(this.value);
          }
          this.editor.addListener('contentChange', () => {
            this.editorContent = this.editor.getContent();
            var contentTxt = this.editor.getContentTxt();
            if (contentTxt == '' && this.editorContent.indexOf('img') < 0) {
              this.$emit('input', '');
            } else {
              this.$emit('input', this.editorContent);
              this.$emit('change', this.editorContent, contentTxt);
            }
          });
          this.upload();
          clearTimeout(timer);
        });
      });
    },
    beforeUpload(file) {
      var arr = file.name.split(".")
      var extand = arr[arr.length - 1];
      if (this.accept.indexOf(extand) >= 0) {
        return true;
      } else {
        this.func.message("error", `不支持的文件格式`);
        return false;
      }
    },
    handleExceed(files, fileList) {
      this.func.message("error", `单次最多支持上传 ${this.limit} 个图片`);
    },
    uploadProgress() {
      this.editorUpLoading = true;
    },
    uploadSuccess(res) {
      this.editorUpLoading = false;
      if (res.success) {
        var file = res.response.files;
        var url = res.response.fileSource;
        if (".png,.jpg,.jpeg,.gif,.bmp,.gif".indexOf(file.fileExtend) >= 0) {
          this.editor.execCommand('insertimage', {
            src: url,
          });
        }
        if (".mp3,.wav".indexOf(file.fileExtend) >= 0) {
          this.editor.execCommand('inserthtml', '<audio src="' + url + '" controls></audio><br>');
        }
        if (".mp4,.avi,.wmv,.mpeg,.remvb".indexOf(file.fileExtend) >= 0) {
          this.editor.execCommand('inserthtml', '<br><video src="' + url + '" controls style="height:200px;"></video><br>');
        }
      }
    },
    uploadError() {
      this.editorUpLoading = false;
      this.func.message("error", '文件上传出错');
    },
    upload() {
      var simpleupload = document.querySelector("#" + this.ueditorId + " .edui-for-simpleupload");
      var eduiBody = simpleupload.querySelector(".edui-button-body");
      let that = this;
      if (simpleupload) {
        simpleupload.onclick = function () {
          document.getElementById(that.fileUploadId).click();
        };
        eduiBody.setAttribute("title", "图片、音频、视频上传")
      };
    }
  }
}
</script>

<style>
.edui-default .edui-editor-iframeholder {
  background-color: #f4f8fb;
}
div.edui-box {
  vertical-align: middle !important;
}
.edui-for-simpleupload .edui-state-disabled .edui-icon {
  opacity: 1 !important;
  filter: alpha(opacity=100) !important;
}

.edui-for-simpleupload .edui-state-disabled:hover .edui-button-wrap {
  background-color: #fff5d4 !important;
  padding: 0 !important;
  border: 1px solid #dcac6c !important;
}
.edui-editor div {
  line-height: 20px !important;
}
.edui-default .edui-editor-bottomContainer {
  display: none;
}
.edui-default
  .edui-toolbar
  .edui-for-fontsize
  .edui-combox-body
  .edui-button-body {
  width: 40px;
}
.ueditor .edui-for-simpleupload .edui-icon {
  background-image: url("/static/ueditor/ue-upload.png") !important;
  background-position: 0 0 !important;
  background-size: contain !important;
}
.edui-editor {
  position: relative;
}
</style>
